import {
  Button,
  DatePicker,
  Drawer,
  Input,
  Modal,
  Popconfirm,
  Space,
  Table,
} from "antd";
import styles from "./Timetable.module.css";
import { LeftCircleOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "../../components/Toast/Toast";
import {
  Countdown,
  HistoryType,
  TimerType,
} from "../Functions/children/Timer/Timer";
// import { getTimeDiff } from "../../utils/utils/timeDiff";
import React from "react";
import { timerApi } from "../../utils/backend/server";
import { useAppDispatch, useAppSelector } from "../../utils/store/hooks";
import { fetchTimerList, updateTimerList } from "../../utils/store/timerSlice";

// interface dataType {
//   key: number;
//   name: string;
//   history: number[];
// }

const HistoryModal = (props: {
  historyModal: boolean;
  dataList: HistoryType[];
  closeModal: () => void;
  // removeHistory: (key: number) => void;
  // updateTimerList: () => void;
}) => {
  const dispatch = useAppDispatch();

  const transformTime = (time: number) => {
    const date = new Date(time);

    return `${date.getFullYear()}-${
      date.getMonth() + 1
    }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  };

  // useEffect(() => {
  //   console.log(props.dataList, "datalist");
  // }, [props.dataList]);
  return (
    <Drawer
      title="history"
      open={props.historyModal}
      onClose={props.closeModal}
    >
      <div className={styles.hisModalBox}>
        {props.dataList?.map((val) => (
          <Popconfirm
            key={val.id}
            title="remove from history?"
            onConfirm={() => {
              // console.log(val);
              // props.removeHistory(val.id);
              timerApi.removeTimerHistory(val.id).then(() => {
                toast("remove success!");
                // props.updateTimerList();
                dispatch(fetchTimerList());
              });
            }}
          >
            <p>{transformTime(Number(val.time) || 0)}</p>
          </Popconfirm>
        )) ||
          "how's that even possible that you have no history, everyone has their own history"}
      </div>
    </Drawer>
  );
};

// const CustomModal = (props: { open: boolean }) => {
//   return (
//     <Modal open={props.open} onOk={(e) => {}}>
//       <DatePicker showTime onChange={(e) => {}} onOk={(e) => {}} />
//       <TimePicker
//         format={"HH:mm"}
//         onChange={(e) => {
//           console.log(e);
//         }}
//       />
//     </Modal>
//   );
// };

const AddModal = (props: {
  open: boolean;
  close: (updateList: boolean) => void;
  list: TimerType[];
  // cloud: myBack;
}) => {
  const [input, setInput] = useState("");
  const [memo, setMemo] = useState("");
  // const updateDataList = (name: string, memo: string) => {
  //   let res = [
  //     ...props.list,
  //     {
  //       name: name,
  //       history: [Date.now()],
  //       key: props.list.length,
  //       memo: memo,
  //     },
  //   ];
  //   return props.cloud.setObj(TIMETABLE_KEY, { list: res });
  // };
  return (
    <Modal
      open={props.open}
      onOk={() => {
        if (!input) {
          toast("please enter name for new table entry!");
          return;
        }

        timerApi.addTimer(input, memo).then(() => {
          props.close(true);
          toast("add success");
        });
        // updateDataList(input, memo)
        //   .then(() => {
        //     props.close(true);
        //     toast("success");
        //   })
        //   .catch((err: object) => {
        //     toast(JSON.stringify(err));
        //   });
      }}
      onCancel={() => props.close(false)}
      okText="add"
    >
      <div className={styles.inputBox}>
        <label>
          <span>name: </span>
          <Input value={input} onChange={(e) => setInput(e.target.value)} />
        </label>
        <label>
          <span>memo: </span>
          <Input value={memo} onChange={(e) => setMemo(e.target.value)} />
        </label>
      </div>
    </Modal>
  );
};

// const TIMETABLE_KEY = "65cb0d0f6658614f41d44c94";
// const { RangePicker } = DatePicker;
export type refreshTypeCallBackType = (data: TimerType[]) => void;

export default () => {
  const [addModalStatus, setAddModalStatus] = useState(false);
  const to = useNavigate();
  // const cloud = backend.getInstance();
  // const [dataList, setDataList] = useState<TimerType[]>([]);
  const dataList = useAppSelector((state) => state.timer).timerList;
  const dispatch = useAppDispatch();
  const [historyModal, setHistoryModal] = useState<{
    status: boolean;
    key: number | string;
    dataList: HistoryType[];
  }>({
    status: false,
    key: -1,
    dataList: [],
  });

  const columns = [
    {
      title: "Name",
      dataIndex: "name",
    },
    {
      title: "Last",
      dataIndex: "id",
      render: (_: string, entry: TimerType, _2: number) => {
        if (!entry.history) return "...";

        const his = entry.history[0];

        if (!his) return "loading...";

        const time = Number(his.time) || 0;

        return <Countdown timeStamp={time} key={his.id} />;
      },
    },
    {
      title: "priority",
      render: (_: string, entry: TimerType) => {
        return (
          <Button
            onClick={async () => {
              await timerApi.setPriority(entry.id);
              refresh();
            }}
            type="primary"
          >
            set First
          </Button>
        );
      },
    },
  ];
  // const [timeCal, setTimeCal] = useState<string>("");
  // const [custom, setCustom] = useState({
  //   status: false,
  // });

  // const refresh = async () => {
  //   // const obj = await cloud.getObj(TIMETABLE_KEY);
  //   // setDataList(obj.get("list"));
  // }

  /**
   cb: refreshTypeCallBackType = () => {}
   */
  const refresh = () => {
    dispatch(fetchTimerList());
    // timerApi.getTimerList().then((data) => {
    //   // if (data.length <= 0) return;
    //   // setDataList(data);
    //   cb && cb(data);
    // });
  };

  // const updateList = (list: TimerType[], success?: () => void) => {
  //   cloud.setObj(TIMETABLE_KEY, { list }).then(() => {
  //     refresh();
  //     success && success();
  //   });
  // };

  useEffect(() => {
    refresh();
  }, []);

  return (
    <div className={styles.box}>
      <div className={styles.title}>
        <LeftCircleOutlined
          style={{ fontSize: "20px", color: "#08c" }}
          onClick={() => {
            // to("/functions");
            to(-1);
          }}
        />
        <h1>Timetable:</h1>
      </div>
      <Table
        pagination={false}
        dataSource={dataList}
        columns={columns}
        rowKey={"id"}
        expandable={{
          expandedRowRender: (record) => (
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  // record.history = [Date.now(), ...record.history];
                  // const res = dataList.map((val) => {
                  //   return val.key === record.key ? record : val;
                  // });
                  timerApi
                    .addTimerHistory(record.id, new Date().valueOf().toString())
                    .then(() => {
                      toast("reset success");
                      refresh();
                    });
                  // updateList(res);
                }}
              >
                now
              </Button>
              <DatePicker
                showTime
                inputReadOnly
                onOk={(e) => {
                  const val = e.valueOf();
                  timerApi
                    .addTimerHistory(record.id, val.toString())
                    .then(() => {
                      toast("update history success");
                      refresh();
                    });

                  // record.history = [...record.history, val].sort(
                  //   (a, b) => b - a
                  // );
                  // const res = dataList.map((val) => {
                  //   return val.key === record.key ? record : val;
                  // });
                  // updateList(res);
                }}
              />

              <Popconfirm
                title="Delete the entry"
                description="Are you sure to delete this entry?"
                okText="Yes"
                cancelText="No"
                onConfirm={() => {
                  timerApi.removeTimer(record.id).then(() => {
                    refresh();
                  });
                  // let res = dataList.filter((val) => val.key !== record.key);
                  // cloud.setObj(TIMETABLE_KEY, { list: res }).then(() => {
                  //   refresh();
                  // });
                }}
              >
                <Button danger type="primary">
                  delete
                </Button>
              </Popconfirm>

              <Button
                type="default"
                onClick={() => {
                  setHistoryModal({
                    status: true,
                    key: record.id,
                    dataList: record.history,
                  });
                }}
              >
                history
              </Button>
            </Space>
          ),
          rowExpandable: (record) => record.name !== "Not Expandable",
        }}
        footer={() => {
          return (
            <Space>
              <Button onClick={() => setAddModalStatus(true)} type="primary">
                add
              </Button>
            </Space>
          );
        }}
      />

      {/* <CustomModal open={custom.status} /> */}
      <AddModal
        open={addModalStatus}
        close={(val) => {
          if (val) {
            refresh();
          }
          setAddModalStatus(false);
        }}
        list={dataList}
        // cloud={cloud}
      />

      <HistoryModal
        closeModal={() => {
          setHistoryModal({
            status: false,
            key: -1,
            dataList: [],
          });
        }}
        dataList={historyModal.dataList}
        historyModal={historyModal.status}
        // updateTimerList={() => {
        //   refresh((data) => {
        //     setHistoryModal((status) => {
        //       return {
        //         ...status,
        //         dataList:
        //           data.find((data) => data.id === status.key)?.history || [],
        //       };
        //     });
        //   });
        //   // setDataList((data) => {
        //   //   setHistoryModal((status) => {
        //   //     const val = {
        //   //       ...status,
        //   //       dataList: data.find((val) => val.id === status.key).history,
        //   //     };
        //   //     // console.log(val);

        //   //     return val;
        //   //   });
        //   //   return data;
        //   // });
        // }}
        // removeHistory={(removeItemVal) => {
        // record.history = [Date.now(), ...record.history];
        // let tmp: number[] = [];
        // const res = dataList.map((entry) => {
        //   if (entry.key === historyModal.key) {
        //     entry.history = entry.history.filter(
        //       (val) => val !== removeItemVal
        //     );
        //     tmp = entry.history;
        //   }
        //   return entry;
        // });
        // updateList(res, () => {
        //   setHistoryModal((oldVal) => {
        //     return {
        //       ...oldVal,
        //       dataList: tmp,
        //     };
        //   });
        // });
        // }}
      />

      {/* <section className={styles.gap}>
        <h3>time calculator: </h3>
        <RangePicker
          showTime
          onOk={(e) => {
            if (!e[1] || !e[0]) return;
            const timeArr = e.map((val) => val?.valueOf());
            const result = getTimeDiff(
              timeArr[0] as number,
              timeArr[1] as number
            );
            setTimeCal(
              `${result.years}year ${result.months}month ${result.days}day ${result.hours}hour:${result.minutes}minute:${result.seconds}second`
            );
          }}
        />

        <h4>result: {timeCal} </h4>
      </section> */}
    </div>
  );
};
